package scatter.portrait.rest.user.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import scatter.common.rest.controller.BaseAddUpdateQueryFormController;
import scatter.common.rest.exception.BusinessDataNotFoundException;
import scatter.common.rest.validation.DictService;
import scatter.portrait.pojo.user.form.*;
import scatter.portrait.pojo.user.po.PortraitUser;
import scatter.portrait.pojo.user.po.PortraitUserTagsRel;
import scatter.portrait.pojo.user.vo.PortraitUserTagsRelVo;
import scatter.portrait.rest.PortraitConfiguration;
import scatter.portrait.rest.user.service.IPortraitUserTagsRelService;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;
/**
 * <p>
 * 用户和标签关系表 前端控制器
 * </p>
 *
 * @author yw
 * @since 2021-10-09
 */
@Api(tags = "用户和标签相关接口")
@RestController
@RequestMapping(PortraitConfiguration.CONTROLLER_BASE_PATH + "/user/portrait-user-tags-rel")
public class PortraitUserTagsRelController extends BaseAddUpdateQueryFormController<PortraitUserTagsRel, PortraitUserTagsRelVo, PortraitUserTagsRelAddForm, PortraitUserTagsRelUpdateForm, PortraitUserTagsRelPageQueryForm> {
    @Autowired
    private IPortraitUserTagsRelService iPortraitUserTagsRelService;
    @Autowired
    private DictService dictService;

    @ApiOperation("添加用户和标签")
    @PreAuthorize("hasAuthority('PortraitUserTagsRel:add')")
    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    @Override
    public PortraitUserTagsRelVo add(@RequestBody @Valid PortraitUserTagsRelAddForm addForm) {
        // 这里是手动配置
        String idByGroupCodeAndValue = dictService.getIdByGroupCodeAndValue(PortraitUser.FeatureTagSourceGroupCode.feature_tag_source.groupCode(),
                PortraitUser.FeatureTagSourceDictItem.manual.itemValue());
        addForm.setSourceDictId(idByGroupCodeAndValue);
        return super.add(addForm);
    }
    @ApiOperation("根据ID查询用户和标签")
    @PreAuthorize("hasAuthority('PortraitUserTagsRel:queryById')")
    @GetMapping("/{id}")
    @ResponseStatus(HttpStatus.OK)
    @Override
    public PortraitUserTagsRelVo queryById(@PathVariable String id) {
        return super.queryById(id);
    }

    @ApiOperation("根据ID删除用户和标签")
    @PreAuthorize("hasAuthority('PortraitUserTagsRel:deleteById')")
    @DeleteMapping("/{id}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    @Override
    public boolean deleteById(@PathVariable String id) {
        return super.deleteById(id);
    }

    @ApiOperation("根据ID更新用户和标签")
    @PreAuthorize("hasAuthority('PortraitUserTagsRel:update')")
    @PutMapping
    @ResponseStatus(HttpStatus.CREATED)
    @Override
    public PortraitUserTagsRelVo update(@RequestBody @Valid PortraitUserTagsRelUpdateForm updateForm) {
        // 这里是手动配置
        String idByGroupCodeAndValue = dictService.getIdByGroupCodeAndValue(PortraitUser.FeatureTagSourceGroupCode.feature_tag_source.groupCode(),
                PortraitUser.FeatureTagSourceDictItem.manual.itemValue());
        updateForm.setSourceDictId(idByGroupCodeAndValue);
        return super.update(updateForm);
    }

    @ApiOperation("不分页查询用户和标签")
    @PreAuthorize("hasAuthority('PortraitUserTagsRel:getList')")
    @GetMapping("/getList")
    @ResponseStatus(HttpStatus.OK)
    @Override
    public List<PortraitUserTagsRelVo> getList(PortraitUserTagsRelPageQueryForm listPageForm) {
         return super.getList(listPageForm);
    }

    @ApiOperation("分页查询用户和标签")
    @PreAuthorize("hasAuthority('PortraitUserTagsRel:getPage')")
    @GetMapping("/getPage")
    @ResponseStatus(HttpStatus.OK)
    @Override
    public IPage<PortraitUserTagsRelVo> getPage(PortraitUserTagsRelPageQueryForm listPageForm) {
         return super.getPage(listPageForm);
    }

    @ApiOperation("用户分配标签")
    @PreAuthorize("hasAuthority('PortraitUserTagsRel:single:userAssignUserTags')")
    @PostMapping("/user/assign/usertags")
    @ResponseStatus(HttpStatus.CREATED)
    public Boolean userAssignUserTags(@RequestBody @Valid UserAssignUserTagsForm cf) {
        // 这里是手动配置
        String idByGroupCodeAndValue = dictService.getIdByGroupCodeAndValue(PortraitUser.FeatureTagSourceGroupCode.feature_tag_source.groupCode(),
                PortraitUser.FeatureTagSourceDictItem.manual.itemValue());
        return iBaseService.removeAndAssignRel(cf.getUserId(),
                cf.getCheckedUserTagsIds(),
                cf.getUncheckedUserTagsIds(),
                cf.getIsLazyLoad(),
                PortraitUserTagsRel::getUserId,
                PortraitUserTagsRel::getUserTagsId,
                (relDto)->new PortraitUserTagsRel().setUserId(relDto.getMainId()).setUserTagsId(relDto.getOtherId()).setSourceDictId(idByGroupCodeAndValue));
    }

    @ApiOperation("根据用户ID查询已分配的标签id")
    @PreAuthorize("hasAuthority('PortraitUserTagsRel:single:queryByUserId')")
    @GetMapping("/user/{userId}")
    @ResponseStatus(HttpStatus.OK)
    public List<String> queryByUserId(@PathVariable String userId) {
        List<PortraitUserTagsRel> rels = iPortraitUserTagsRelService.getByUserId(userId);
        if (isEmpty(rels)) {
            throw new BusinessDataNotFoundException("数据不存在");
        }

        return rels.stream().map(item -> item.getUserTagsId()).collect(Collectors.toList());
    }

    @ApiOperation("清空用户下的所有标签")
    @PreAuthorize("hasAuthority('PortraitUserTagsRel:single:deleteByUserId')")
    @DeleteMapping("/user/{userId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public Boolean deleteByUserId(@PathVariable String userId) {
        return iBaseService.removeAssignRel(userId,PortraitUserTagsRel::getUserId);
    }


    @ApiOperation("标签分配用户")
    @PreAuthorize("hasAuthority('PortraitUserTagsRel:single:userTagsAssignUser')")
    @PostMapping("/usertags/assign/user")
    @ResponseStatus(HttpStatus.CREATED)
    public Boolean userTagsAssignUser(@RequestBody @Valid UserTagsAssignUserForm cf) {
        // 这里是手动配置
        String idByGroupCodeAndValue = dictService.getIdByGroupCodeAndValue(PortraitUser.FeatureTagSourceGroupCode.feature_tag_source.groupCode(),
                PortraitUser.FeatureTagSourceDictItem.manual.itemValue());
        return iPortraitUserTagsRelService.removeAndAssignRel(cf.getUserTagsId(),
                cf.getCheckedUserIds(),
                cf.getUncheckedUserIds(),
                cf.getIsLazyLoad(),
                PortraitUserTagsRel::getUserTagsId,
                PortraitUserTagsRel::getUserId,
                (relDto)->new PortraitUserTagsRel().setUserTagsId(relDto.getMainId()).setUserId(relDto.getOtherId()).setSourceDictId(idByGroupCodeAndValue));
    }

    @ApiOperation("根据标签ID查询已分配的用户id")
    @PreAuthorize("hasAuthority('PortraitUserTagsRel:single:queryByUserTagsId')")
    @GetMapping("/usertags/{userTagsId}")
    @ResponseStatus(HttpStatus.OK)
    public List<String> queryByUserTagsId(@PathVariable String userTagsId) {
        List<PortraitUserTagsRel> rels = iPortraitUserTagsRelService.getByUserTagsId(userTagsId);
        if (isEmpty(rels)) {
            throw new BusinessDataNotFoundException("数据不存在");
        }
        return rels.stream().map(item -> item.getUserTagsId()).collect(Collectors.toList());
    }

    @ApiOperation("清空标签下的所有用户")
    @PreAuthorize("hasAuthority('PortraitUserTagsRel:single:deleteByUserTagsId')")
    @DeleteMapping("/usertags/{userTagsId}")
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public Boolean deleteByUserTagsId(@PathVariable String userTagsId) {
        return iPortraitUserTagsRelService.removeAssignRel(userTagsId,PortraitUserTagsRel::getUserTagsId);
    }
}
